<template>
  <div class="card-main w100p bgf5f6 bgfff"
       :style="{height: mainHeight+'px'}">

    <scroll-view :style="{height: scrollContentHeight+'px'}"
                 class="dynamic-content"
                 :scroll-y="true"
                 :enable-back-to-top="true"
                 :scroll-anchoring="true"
                 @scrolltoupper='scrolltoupper'
                 @scrolltolower="scrolltolower">
      <!--我的 / 默认 名片-->
      <div class="bgfff pt15 pl16 pr15">
        <!-- <div class="bradius10 bgfff "
             v-if="hasCard && card_msg.cardId"> -->
             <div class="bradius10"
                  v-for="(v,k) in mylists"
                  :key="k">
               <div class="bgfff bradius10">
                  <!-- <GetPhoneNumber @next="toIndex('index', card_msg.companyId, card_msg.cardId)"> -->
                  <MeCard :card_msg="v"
                          :type="'plus'"
                          :hasCard="hasCard"
                          :isdel="false"
                          :index="0"
                          @click.native="toIndex('mine', v.companyId, v.cardId, v.userId, v.roleId)"
                          @moreTap="moreTap">
                  </MeCard>
                  <!-- </GetPhoneNumber> -->
               </div>
             </div>
        <!-- </div> -->
      </div>

      <!--bottom-->
      <!-- <div class="textc lh70 fs12 ca8 bgf5f6" v-if="nodata">- 到底了，看看其他的吧 -</div> -->

      <SelectorOne :title="'操作'"
                   :status="operateShow"
                   :allClass="operateTypes"
                   @closeModal="operateShow = !operateShow"
                   @choose_tap="choose_tap"></SelectorOne>

      <div v-if="isShowNotice&& noticeList.length&&!isLogin"
           @click="isShowNotice=false">
        <AppNotice :noticeList="noticeList"></AppNotice>
      </div>
    </scroll-view>

  </div>

</template>

<script>
import BusinessCard from '@/components/BusinessCard' //
import MeCard from '@/components/MeCard' //
import SelectorOne from '@/components/selectorOne' //
import GetPhoneNumber from '@/components/getPhoneNumber' //
import getPhoneNumberCard from '@/components/getPhoneNumberCard' //
import AppNotice from '@/components/AppNotice'
import { mapActions } from 'vuex';
import WXAJAX from '../../utils/request'
import util from '../../utils/index'
import HandleLogin from '@/utils/handleLogin'
import { addShareRecord } from '@/utils/behavior';
export default {
  name: '',
  components: { MeCard, BusinessCard, SelectorOne, GetPhoneNumber, getPhoneNumberCard, AppNotice },
  data() {
    return {
      searchkey: '',
      last_searchkey: '',
      isfocus: false,
      mine_card: {},
      lists: [],
      mylists: [],
      hasCard: wx.getStorageSync('hasCard') || false,//是否已经有名片
      isLogin: HandleLogin.returnIsLogin() || false,//是否已经登录
      addInfo: false,//显示添加的按钮
      card_msg: {
        picchecked: '',
        username: '',
        tel: '',
        wx: '',
        company_wx: '',
        email: '',
        post: '',
        company: '',
        company_logo: ''
      },
      phoneMsg: {
        phoneData: '',
        iv: '',
      },
      //名片操作
      operateID: 0,
      operateShow: false,
      operateTypes: [
        { name: '置顶', id: 'top' },
        // {name:'删除' , id:'del'},
      ],
      cardId: 0,//删除时使用
      isfresh: false,
      page: 1,
      isLoading: false,//是否在加载
      nodata: false,//是否已经没有数据
      isShowLogin: false,
      isShowNotice: true, // 是否显示公告
      noticeList: [],  // 公告列表
      avatarUrl: '',//用户的头像地址,
      isShowLoginGuide: false, //是否显示登录引导页,
      scrollContentHeight: 0, //中间滚动区域的高度
      mainHeight: 0, //整体高度
      total:0,//总页数
    }
  },
  onReachBottom() {
    // let v = this ;
    // v.getAllCard();

  },
  onShareAppMessage(e) {
    console.log(e.target.dataset)

    let cardId = e.target.dataset.cardid;
    let companyId = e.target.dataset.companyid;
    let companyName = e.target.dataset.companyname;
    let imgurl = e.target.dataset.logo || 'https://thirdwx.qlogo.cn/mmopen/vi_32/VTFUkCPPwZdpB21d9dtLXCdRra3OyEboJvo0KGcczrnGTX7uKhsyTOwCywAx3F2xicrGb8wYq8H9VpYLR0W5e8A/132'
    // let shareId = await addShareRecord(companyId, 1, cardId);
    let uuid = cardId + '' + new Date().getTime();
    addShareRecord(companyId, 1, cardId, uuid).then(res => { }, err => { });
    let { sharespeech = '', position, name } = e.target.dataset;
    sharespeech = sharespeech.replace('#name#', name).replace('#company#', companyName);
    return {
      title: sharespeech || `您好，我是${companyName}${position || ''}的${name}，敬请惠存!`,
      path: `/pages/index/main?cardId=${cardId}&companyId=${companyId}&goType=1&shareId=${uuid}`,
      imageUrl:imgurl,
      success(e) {
        wx.showShareMenu({
          withShareTicket: true
        })
      },
      fail(e) {
        console.log('失败-- ', e);
      }
    }
  },
  onUnload() {
    this.isShowLogin = false;
    this.isShowNotice = true;
    this.noticeList = [];
  },
  async onPullDownRefresh() {
    console.log("下拉刷新onPullDownRefresh")
    // to doing..
    // 停止下拉刷新
    wx.showNavigationBarLoading();
    this.page = 1;
    this.card_msg = {};
    this.searchkey = '';
    this.lists = [];
    this.nodata = false;
    this.isLoading = false;
    this.getAllCard();
    wx.stopPullDownRefresh();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
    }, 300)
  },
  onShow() {
    this.searchkey = '';
    this.isfresh = true;
    this.card_msg = {};
    this.page = 1;
    this.isLogin = HandleLogin.returnIsLogin() || false;
    this.hasCard = wx.getStorageSync('hasCard') || false;
    this.avatarUrl = wx.getStorageSync('avatarUrl');

    this.getAllCard();
  },

  onHide() {
    this.addInfo = false;
  },
  async mounted() {
    let a = await util.systemIfo();
    let navHeight = getApp().globalData.navHeight;
    this.mainHeight = a.windowHeight;
    this.scrollContentHeight = a.windowHeight - navHeight;
  },
  methods: {
    ...mapActions(['setPhone']),
    //点击名片的拨打电话,回调需要登录
    needLogin() {
      this.isLogin = false;
      this.isShowLoginGuide = true;
    },
    //隐藏登录引导
    cancelLoginGuide() {
      this.isShowLoginGuide = false;
    },
    //下拉刷新
    scrolltoupper() {
      this.page = 1;
      this.searchkey = '';
      // this.card_msg = {} ;
      // this.lists = [] ;
      this.nodata = false;
      this.isLoading = false;
      this.getAllCard();
    },
    //上拉加载更多
    scrolltolower() {
      this.getAllCard();
    },
    //点击立即创建名片,因为没有登录,所以授权成功以后,会有登录成功的回调,回调成功以后,跳转到名片创建页面
    loginSuccess(url) {
      this.isLogin = true;
      this.hasCard = wx.getStorageSync('hasCard') || false;
      this.avatarUrl = wx.getStorageSync('avatarUrl') || '';

      if (url && url === 'insert') {
        // wx.navigateTo({ url: "../editCard/main?type=add&goType=1" });
        wx.navigateTo({ url: "/pages/createCard/chooseIdentity/main?goType=1" });
      } else {
        this.page = 1;
        this.getAllCard();
      }
      //头像登录成功的回调
    },
    getNotice() {
      WXAJAX.POST({}, '', '/notice/selectEffectiveList','','',2).then(res => {
        this.noticeList = res || [];
      });
    },
    shareApp(companyId, cardId, companyName, name, logo) {
      console.log('companyId' + companyId)
      console.log('companyId' + cardId)
      console.log('companyId' + companyName)
      console.log('companyId' + name)
      console.log('companyId' + logo)
      return
      this.onShareAppMessage(companyId, cardId, companyName, name, logo)
    },
    createCard() {
      this.toCreatePage();
    },
    search_focus() {
      this.isfocus = true;
    },
    search_confirm() {
      if (this.searchkey === this.last_searchkey) {
        return;
      }
      wx.showLoading();
      this.page = 1;
      this.card_msg = {};
      this.lists = [];
      this.nodata = false;
      this.isLoading = false;
      this.getAllCard();
    },
    page_turn(url) {
      this.addInfo = false;
      wx.navigateTo({ url: '../' + url + '/main' })
    },
    toIndex(url, companyid, cardid,userId,roleId) {//进入首页
      wx.setStorageSync('isBoss' , roleId != 0 ) ;
      console.log('isBoss',roleId != 0)
      wx.setStorageSync('SELFCOMPANYID', companyid);/*id*/
      wx.setStorageSync('SELFCARDID', cardid);/*id*/
      wx.setStorageSync('userId', userId);/*id*/
      this.addInfo = false;
      wx.switchTab({ url: '../' + url + '/main?cardId=' + cardid + '&companyId=' + companyid + '&type=1'});
    },
    getPhoneNumber(e) {
      this.phoneMsg.phoneData = e.encryptedData;
      this.phoneMsg.iv = e.iv;
    },
    getAllCard() {
      let v = this;
      if (v.isLoading) {
        return
      }
      v.isLoading = true;
      //biaoji meiyou1
      WXAJAX.POST({
        name: this.searchkey,
        pageNum: v.page,
      }, '', '/businessCard/findMyCards','','',2).then((data) => {
        this.last_searchkey = this.searchkey;
        // state : 1 -- 默认 ， 2 -- 浏览记录 ， 3 -- 自己的
        if (data && data.list) {
          let datas = [];
          let mydatas = [];
          this.total = data.total;
          data.list.forEach(function (i, k) {
            const cardData = {
              picchecked: i.logo || '',
              username: i.name || '',
              tel: i.phone || '',
              wx: i.personalWx || '',
              company_wx: i.companyWx || '',
              email: i.email || '',
              post: i.position || '',
              company: i.companyName,
              company_logo: i.companyLogo,
              cardId: i.cardId,
              companyId: i.companyId,
              recordId: i.recordId,
              shareSpeech: i.shareSpeech || '',
              userId: i.userId || '',
              roleId: i.roleId || '',
            };

              v.card_msg = cardData;
              mydatas.push(cardData);
              wx.setStorageSync("SELFCARDID", cardData.cardId);
              wx.setStorageSync("SELFCOMPANYID", cardData.companyId);
              wx.setStorageSync("currentUserId", cardData.userId);


          });
          if (v.page === 1) {
            this.mylists = mydatas;
          } else {
            this.mylists.push(...mydatas);
          }

          v.page++;

          if (!v.hasCard) {
            v.addInfo = true;
          }
        }
        setTimeout(function () {
          v.nodata = true;
          v.isLoading = false;
        }, 500);

        wx.hideLoading();
      }).catch((err) => {
        wx.hideLoading();
      });


    },
    moreTap(recordId, cardId, isdel) {//更多操作
      this.operateID = recordId;
      this.cardId = cardId;
      if (isdel) {
        this.operateTypes = [
          { name: '置顶', id: 'top' },
          // {name:'删除' , id:'del'},
        ];
      } else {
        this.operateTypes = [
          { name: '置顶', id: 'top' },
        ];
      }
      this.operateShow = true;
    },
    choose_tap(type) {//名片操作
      this.operateShow = false;

      wx.showLoading();

      let _url = '',
        id = 0;
      if (type === 'top') {
        _url = '/businessCard/isTop';
        id = this.cardId;
      } else {
        _url = '/businessCard/delSeeCard';
        id = this.cardId;
      }

      WXAJAX.POST({
        cardId: id
      }, '', _url,'','',2).then((data) => {

        wx.hideLoading();
        wx.showToast({
          title: '操作成功！',
          duration: 2000,
          icon: 'none'
        });
        this.page = 1;
        this.card_msg = {};
        this.searchkey = '';
        this.lists = [];
        this.nodata = false;
        this.isLoading = false;
        this.getAllCard();

      }).catch((err) => {
        wx.hideLoading();
      });

    }
  }
}
</script>

<style>
.card-main {
  width: 100%;
  height: 100%;
}
.searchText {
  cursor: auto;
  display: inline-block;
  height: 68upx;
  max-width: 100%;
  padding-left: 20upx;
  text-align: left;
  line-height: 68upx;
  font-size: 28upx;
  color: #a8a8a8;
}
.search {
  justify-content: center;
}

.search.focus {
  justify-content: flex-start;
}

.search.focus input {
  width: auto;
}
page {
  width: 100%;
  height: 100%;
}
.add_card {
  position: fixed;
  right: 0;
  bottom: 90upx;
  z-index: 99;
  padding-right: 30upx;
  padding-left: 30upx;
  box-sizing: border-box;
  text-align: right;
}

.create-btn {
  transition: all 0.8s ease-in-out;
  display: inline-flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 30upx;
  border-radius: 1998upx;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  color: white;
  position: relative;
}
.create-btn .create {
  flex-grow: 1;
  text-align: right;
}

.width-max {
  width: 100%;
}

.create-btn img {
  flex: 0 0 60upx;
}
.my-card-case {
  height: 36upx;
}
.card-case-num-img {
  /* display: inline-block; */
  width: 32upx;
  height: 32upx;
  /* border: 1upx dashed #444 */
}
.separator {
  display: inline-block;
  width: 8upx;
  height: 32upx;
  background: #51cdcb;
}
</style>
